"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { Users, Brain, HandMetal, AlertTriangle } from "lucide-react"
import { XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Area, AreaChart } from "recharts"

// 模拟API接口
interface StudentAnalyticsData {
  attendanceCount: number
  totalStudents: number
  attendanceRate: number
  attentionRate: number
  participationRate: number
  distractionEvents: {
    type: string
    count: number
  }[]
  trendData: {
    time: string
    attention: number
    participation: number
  }[]
}

interface StudentAnalyticsProps {
  isActive: boolean
}

export function StudentAnalytics({ isActive }: StudentAnalyticsProps) {
  const [data, setData] = useState<StudentAnalyticsData | null>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (!isActive) {
      return
    }

    setLoading(true)

    // 模拟API调用
    const fetchData = () => {
      // 在实际应用中，这里会调用后端API获取实时分析数据
      const mockData: StudentAnalyticsData = {
        attendanceCount: 32,
        totalStudents: 35,
        attendanceRate: 91.4,
        attentionRate: 78.5,
        participationRate: 65.2,
        distractionEvents: [
          { type: "使用手机", count: 4 },
          { type: "交谈", count: 3 },
          { type: "睡觉", count: 1 },
          { type: "离开座位", count: 2 },
        ],
        trendData: [
          { time: "0分钟", attention: 70, participation: 60 },
          { time: "5分钟", attention: 75, participation: 55 },
          { time: "10分钟", attention: 65, participation: 65 },
          { time: "15分钟", attention: 80, participation: 50 },
          { time: "20分钟", attention: 85, participation: 55 },
          { time: "25分钟", attention: 75, participation: 45 },
          { time: "30分钟", attention: 90, participation: 65 },
        ],
      }

      setData(mockData)
      setLoading(false)
    }

    // 立即获取一次数据
    fetchData()

    // 设置定时器，模拟实时更新
    const intervalId = setInterval(() => {
      if (isActive) {
        fetchData()
      }
    }, 5000)

    return () => {
      clearInterval(intervalId)
    }
  }, [isActive])

  if (!isActive) {
    return <div className="p-8 text-center text-muted-foreground">请点击"开始监控"按钮启动学生行为分析</div>
  }

  if (loading && !data) {
    return <div className="p-8 text-center text-muted-foreground">正在加载学生分析数据...</div>
  }

  if (!data) {
    return <div className="p-8 text-center text-muted-foreground">无法获取学生分析数据</div>
  }

  return (
    <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4 mt-6">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-sm font-medium">出勤情况</CardTitle>
          <Users className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">
            {data.attendanceCount}/{data.totalStudents}
          </div>
          <p className="text-xs text-muted-foreground">出勤率 {data.attendanceRate.toFixed(1)}%</p>
          <Progress className="mt-2" value={data.attendanceRate} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-sm font-medium">专注度</CardTitle>
          <Brain className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{data.attentionRate.toFixed(1)}%</div>
          <p className="text-xs text-muted-foreground">
            {data.attentionRate > 75 ? "良好" : data.attentionRate > 50 ? "一般" : "较差"}
          </p>
          <Progress className="mt-2" value={data.attentionRate} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-sm font-medium">参与度</CardTitle>
          <HandMetal className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{data.participationRate.toFixed(1)}%</div>
          <p className="text-xs text-muted-foreground">
            {data.participationRate > 75 ? "积极" : data.participationRate > 50 ? "一般" : "消极"}
          </p>
          <Progress className="mt-2" value={data.participationRate} />
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-sm font-medium">分心行为</CardTitle>
          <AlertTriangle className="h-4 w-4 text-muted-foreground" />
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">
            {data.distractionEvents.reduce((sum, event) => sum + event.count, 0)}
          </div>
          <div className="mt-2 space-y-1">
            {data.distractionEvents.map((event, index) => (
              <div key={index} className="flex justify-between text-xs">
                <span>{event.type}</span>
                <span>{event.count}次</span>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
      <div className="col-span-full mt-6">
        <Card>
          <CardHeader>
            <CardTitle>学生行为趋势</CardTitle>
            <CardDescription>过去30分钟的学生行为变化趋势</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[250px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart
                  data={data.trendData}
                  margin={{
                    top: 10,
                    right: 30,
                    left: 0,
                    bottom: 0,
                  }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="time" />
                  <YAxis domain={[0, 100]} />
                  <Tooltip formatter={(value) => [`${value}%`]} />
                  <Legend />
                  <defs>
                    <linearGradient id="colorAttention" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#0088FE" stopOpacity={0.8} />
                      <stop offset="95%" stopColor="#0088FE" stopOpacity={0.1} />
                    </linearGradient>
                    <linearGradient id="colorParticipation" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#FF8042" stopOpacity={0.8} />
                      <stop offset="95%" stopColor="#FF8042" stopOpacity={0.1} />
                    </linearGradient>
                  </defs>
                  <Area
                    type="monotone"
                    dataKey="attention"
                    name="专注度"
                    stroke="#0088FE"
                    strokeWidth={2}
                    fill="url(#colorAttention)"
                    activeDot={{ r: 8 }}
                    animationBegin={0}
                    animationDuration={1500}
                    animationEasing="ease-out"
                  />
                  <Area
                    type="monotone"
                    dataKey="participation"
                    name="参与度"
                    stroke="#FF8042"
                    strokeWidth={2}
                    fill="url(#colorParticipation)"
                    activeDot={{ r: 8 }}
                    animationBegin={500}
                    animationDuration={1500}
                    animationEasing="ease-out"
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
